package com.sws.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sws.yygh.hosp.repository.DepartmentRepository;
import com.sws.yygh.hosp.service.DepartmentService;
import com.sws.yygh.model.hosp.Department;
import com.sws.yygh.vo.hosp.DepartmentQueryVo;
import com.sws.yygh.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: Appointment-hospital-registration-system
 * @description:
 * @author:
 * @create: 2022-07-18 14:18
 */
@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        //paramMap数据转换为 Department类型
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);
        //判断是否存在
        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if(targetDepartment != null){
            targetDepartment.setUpdateTime(new Date());
            targetDepartment.setIsDeleted(0);
            departmentRepository.save(targetDepartment);
        }else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //创建pageable对象
        Pageable pageable = PageRequest.of(page-1, limit);
        //创建Example
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);   //改变默认大小写忽略方式：忽略大小写

        Example<Department> example = Example.of(department,matcher);
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department != null){
            String id = department.getId();
            departmentRepository.deleteById(id);
        }
    }

    /**
     * 根据医院编号，查询医院所有科室列表
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();
        //查询 医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        List<Department> departmentList = departmentRepository.findAll(example);
        //根据大科室编号 bigcode 分组，获取每个大科室里面下级子科室
        // java8中流实现分组，将List变成Map，Map中key为大科室编号，value为下级子科室列表
        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //map中entry属性 （key、value的关系）
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            // 获取大科室编号
            String bigCode = entry.getKey();
            // 获取大科室编号对应的全部小科室数据
            List<Department> smallDepartmentList = entry.getValue();
            // 封装大科室
            DepartmentVo bigDepartmentVo = new DepartmentVo();
            bigDepartmentVo.setDepcode(bigCode);
            bigDepartmentVo.setDepname(smallDepartmentList.get(0).getBigname());
            // 封装小科室
            List<DepartmentVo> childs = new ArrayList<>();
            for (Department child : smallDepartmentList) {
                DepartmentVo smallDepartmentVo = new DepartmentVo();
                smallDepartmentVo.setDepcode(child.getDepcode());
                smallDepartmentVo.setDepname(child.getDepname());
                childs.add(smallDepartmentVo);
            }
            bigDepartmentVo.setChildren(childs);
            result.add(bigDepartmentVo);
        }
        return result;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department!=null){
            return department.getDepname();
        }
        return "";
    }
}
